import Axios from 'axios'
import qs from 'qs'
import store from '@/store'
// import router from '@/router'
import md5 from 'js-md5'
import * as utils from '@/utils'

const option = {
  timeout: 30000,
  baseURL: process.env.VUE_APP_BASE_API,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  transformRequest: (data, headers) => {
    if (headers['Content-Type'].search('application/json') !== -1) {
      return JSON.stringify(data)
    } else if (headers['Content-Type'].search('multipart/form-data') !== -1) {
      return data
    } else {
      return qs.stringify(data)
    }
  }
}
let showToast = true

const axios = Axios.create(option)

// 添加请求拦截器
axios.interceptors.request.use(
  (config) => {
    showToast = config.showToast !== false
    const clientid = 'dvs'
    const token = utils.uglifySecret()
    const timestamp = String(+new Date())
    const nonce = String(utils.createRandom(3))
    const requestUri =
      process.env.NODE_ENV === 'development'
        ? config.url.replace(process.env.VUE_APP_BASE_API, '')
        : config.url
    const requestParamsString = config.data
      ? utils.objectToParams(config.data)
      : config.params
      ? utils.objectToParams(config.params)
      : ''
    const signature = md5(token + timestamp + nonce + requestUri + requestParamsString)
    const signatureversion = '2.0.0'
    config.headers = {
      ...config.headers,
      clientid,
      timestamp,
      nonce,
      signatureversion,
      requestParamsString,
      signature,
      requestUri,
      Authz: store.state.userInfo.token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
axios.interceptors.response.use(
  (response) => {
    // 错误拦截判断
    if (response.data && !response.data.success) {
      window.common.hideLoading()
      // , time: 900000
      if (showToast) {
        window.common.showToast({ text: response.data.message })
      }
      return response.data
    }
    // window.common.hideLoading()
    return {
      data: response.data,
      status: response.status,
      headers: response.headers,
      statusText: response.statusText
    }
  },
  (error) => {
    window.common.hideLoading()
    try {
      if (error.response.data.errorCode === 403004) {
        window.common.showToast({ text: '用户登录已过期，请退出后重新打开!', time: 0 })
      } else {
        error.message.indexOf('timeout') !== -1
          ? window.common.showToast('请求超时！')
          : window.common.showToast(error.message)
      }
    } catch (err) {
      window.common.showToast('请求异常！')
    }
    return Promise.reject(error)
  }
)

export default axios
